import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import {User} from './user';
import {USERS} from './users';

@Injectable({
  providedIn: 'root'
})
export class TestService {

  constructor(private http: HttpClient) { }
  getUsers(): Observable<User[]> {
    // return of(USERS);
    return this.http.get<User[]>('api/users')
    .pipe(
      tap(_ => this.log('fetched users')),
      catchError(this.handleError<User[]>('getUsers'))
      );
  }
  getUser(id: number): Observable<User> {
    // return of(USERS.find(user => user.id === id));
    const url = `api/users/${id}`;
    return this.http.get<User>(url)
    .pipe(
      tap(_ => this.log('fetched users')),
      catchError(this.handleError<User>('getUsers'))
      );
  }
  deleteUser(id: number): Observable<boolean> {
    const index = USERS.findIndex(user => user.id === id);
    USERS.splice(index, 1);
    return of(true);
  }
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead
      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);
      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
  private log(message: string) {
    console.log(message);
  }
}


